import sys
import os
import yaml
from pathlib import Path
import argparse

# 导入路径管理器和我们自己的模块
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from src.utils import CONFIG_PATH
from src.fingerprinting.processor import Processor
from src.fingerprinting.hashing import Hasher

def compare_fingerprints(file1_path: Path, file2_path: Path, config_path: Path):
    """
    直接比较两个音频文件的指纹重合度，用于诊断问题。
    Directly compares the fingerprint overlap between two audio files for diagnostics.
    """
    print("="*50)
    print("Fingerprint Comparison Diagnostic Tool")
    print("="*50)

    # 1. 加载配置
    print(f"Loading configuration from: {config_path.name}")
    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)

    # 2. 初始化模块
    processor = Processor(config)
    hasher = Hasher(config['hashing'])

    # --- 处理第一个文件 ---
    print(f"\n[1] Processing Original File: {file1_path.name}")
    try:
        peaks1 = processor.audio_to_peaks(str(file1_path))
        if not peaks1.any():
            print("  -> Error: No peaks found in the original file.")
            return
        fingerprints1 = hasher.peaks_to_fingerprints(peaks1)
        # 我们只关心哈希值本身，所以创建一个集合以便快速比较
        hashes1 = {fp[0] for fp in fingerprints1}
        print(f"  -> Generated {len(peaks1)} peaks and {len(hashes1)} unique fingerprints.")
    except Exception as e:
        print(f"  -> Error processing file: {e}")
        return

    # --- 处理第二个文件 ---
    print(f"\n[2] Processing Sample File: {file2_path.name}")
    try:
        peaks2 = processor.audio_to_peaks(str(file2_path))
        if not peaks2.any():
            print("  -> Error: No peaks found in the sample file.")
            return
        fingerprints2 = hasher.peaks_to_fingerprints(peaks2)
        hashes2 = {fp[0] for fp in fingerprints2}
        print(f"  -> Generated {len(peaks2)} peaks and {len(hashes2)} unique fingerprints.")
    except Exception as e:
        print(f"  -> Error processing file: {e}")
        return

    # --- 对比分析 ---
    print("\n[3] Comparison Results")
    if not hashes1 or not hashes2:
        print("  -> Cannot compare because one of the files yielded no fingerprints.")
        return

    # 计算交集
    matching_hashes = hashes1.intersection(hashes2)

    num_matches = len(matching_hashes)
    overlap_percentage = (num_matches / len(hashes2)) * 100

    print(f"  -> Matching Fingerprints: {num_matches}")
    print(f"  -> Sample's Total Unique Fingerprints: {len(hashes2)}")
    print(f"  -> Overlap Percentage: {overlap_percentage:.2f}%")

    print("\n--- Analysis ---")
    if overlap_percentage > 10:
        print("✅ High Overlap: The fingerprinting process seems robust. If recognition still fails, the issue might be in the scoring thresholds or database.")
    elif 0 < overlap_percentage <= 10:
        print("⚠️ Low Overlap: Some fingerprints match, but most do not. This often happens with significant noise or aggressive compression. Recognition may be unreliable.")
    else: # overlap_percentage == 0
        print("❌ No Overlap: The sample's fingerprints are completely different from the original's. This is the reason for the recognition failure. It is very likely caused by audio re-encoding (e.g., saving a clip from an MP3 as a new MP3).")
    print("="*50)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Compare the fingerprints of two audio files.")
    parser.add_argument('original_file', type=Path, help="Path to the original, full audio file.")
    parser.add_argument('sample_file', type=Path, help="Path to the shorter audio sample file.")
    args = parser.parse_args()

    if not args.original_file.exists():
        print(f"Error: Original file not found at '{args.original_file}'")
    elif not args.sample_file.exists():
        print(f"Error: Sample file not found at '{args.sample_file}'")
    else:
        compare_fingerprints(args.original_file, args.sample_file, CONFIG_PATH)
